import { getUserInfo } from '../../../utils/userInfo';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
import getSimilarity from '../utils/getSimilarity';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        showPage: false,
        choice: [], // 选择题
        fill: [], // 填空题
        judgment: [], // 判断题
        explain: [], // 问答题
        other: [], // 其他题
        selectArr: [],
        isRadioSelect: false,
        empty: false,
        time: 30 * 60 * 1000,
    },

    /**
     * 每次点击单选，进行一次题目正确性的判断
     */
    onChange(event) {
        // console.log(event.detail);
        // 单选选中，拿到属于本条的id+选项
        const nowSelectId = event.detail.split('.')[0]
        const nowSelectCont = event.detail.split('.')[1]
        // console.log(nowSelectId, nowSelectCont);
        let { choice, selectArr } = this.data
        choice.forEach((item, index) => {
            if (item._id === nowSelectId) {
                if (selectArr && selectArr.length > 0) {
                    // 数组中已经存在值，如果选中同一题，把答案替换了
                    if (selectArr.some(item => item.currentIndex == index)) {
                        // 找到在selectArr当前项的下标
                        const findId = selectArr.findIndex((item) => item.currentIndex == index)
                        // 替换操作
                        if (item.answer === nowSelectCont) {
                            console.log('true');
                            selectArr.splice(findId, 1, { currentIndex: index, flag: true, answer: item.answer })
                        } else {
                            console.log('false');
                            selectArr.splice(findId, 1, { currentIndex: index, flag: false, answer: item.answer })
                        }
                        // console.log(333,findId);
                    } else {
                        if (item.answer === nowSelectCont) {
                            console.log('true');
                            selectArr.push({ currentIndex: index, flag: true, answer: item.answer })
                        } else {
                            console.log('false');
                            selectArr.push({ currentIndex: index, flag: false, answer: item.answer })
                        }
                    }
                } else {
                    // 数组是空的，相当于第一次添加
                    if (item.answer === nowSelectCont) {
                        console.log('true');
                        selectArr.push({ currentIndex: index, flag: true, answer: item.answer })
                    } else {
                        console.log('false');
                        selectArr.push({ currentIndex: index, flag: false, answer: item.answer })
                    }
                }
            }
        })
        console.log(selectArr);
    },

    // 填空题答案判断
    onBlurFillIpt(e) {
        // console.log(e);
        const { id } = e.currentTarget.dataset;
        const { value } = e.detail;
        // 思路：跟上选择题的序号，输入框每次失焦时，进行一次题目正确性的判断
        let { fill, selectArr } = this.data;
        fill.forEach((item, index) => {
            if (id === item._id) {
                if (selectArr && selectArr.length > 0) {
                    // 数组中已经存在值，如果选中同一题，把答案替换了
                    if (selectArr.some(item => item.currentIndex == index + 10)) {
                        // 找到在selectArr当前项的下标
                        const findId = selectArr.findIndex((item) => item.currentIndex == index + 10);
                        // 替换操作
                        if (item.answer === value) {
                            console.log('true');
                            selectArr.splice(findId, 1, { currentIndex: index + 10, flag: true, answer: item.answer })
                        } else {
                            console.log('false');
                            selectArr.splice(findId, 1, { currentIndex: index + 10, flag: false, answer: item.answer })
                        }
                        // console.log(333,findId);
                    } else {
                        if (item.answer === value) {
                            console.log('true');
                            selectArr.push({ currentIndex: index + 10, flag: true, answer: item.answer })
                        } else {
                            console.log('false');
                            selectArr.push({ currentIndex: index + 10, flag: false, answer: item.answer })
                        }
                    }
                } else {
                    // 数组是空的，相当于第一次添加
                    if (item.answer === value) {
                        console.log('true');
                        selectArr.push({ currentIndex: index + 10, flag: true, answer: item.answer })
                    } else {
                        console.log('false');
                        selectArr.push({ currentIndex: index + 10, flag: false, answer: item.answer })
                    }
                }
            }
        });
        console.log(selectArr);
    },

    // onChangeJudgment 判断题答案判断
    onChangeJudgment(e) {
        const nowSelectId = e.detail.split('.')[0];
        const nowSelectCont = e.detail.split('.')[1]; // true 和 false两种值
        let { judgment, selectArr } = this.data;
        judgment.forEach((item, index) => {
            if (item._id === nowSelectId) {
                if (selectArr && selectArr.length > 0) {
                    // 数组中已经存在值，如果选中同一题，把答案替换了
                    if (selectArr.some(item => item.currentIndex == index + 15)) {
                        // 找到在selectArr当前项的下标
                        const findId = selectArr.findIndex((item) => item.currentIndex == index + 15);
                        // 替换操作
                        if (item.answer === nowSelectCont) {
                            console.log('true');
                            selectArr.splice(findId, 1, { currentIndex: index + 15, flag: true, answer: item.answer })
                        } else {
                            console.log('false');
                            selectArr.splice(findId, 1, { currentIndex: index + 15, flag: false, answer: item.answer })
                        }
                        // console.log(333,findId);
                    } else {
                        if (item.answer === nowSelectCont) {
                            console.log('true');
                            selectArr.push({ currentIndex: index + 15, flag: true, answer: item.answer })
                        } else {
                            console.log('false');
                            selectArr.push({ currentIndex: index + 15, flag: false, answer: item.answer })
                        }
                    }
                } else {
                    // 数组是空的，相当于第一次添加
                    if (item.answer === nowSelectCont) {
                        console.log('true');
                        selectArr.push({ currentIndex: index + 15, flag: true, answer: item.answer })
                    } else {
                        console.log('false');
                        selectArr.push({ currentIndex: index + 15, flag: false, answer: item.answer })
                    }
                }
            }
        })
        console.log(selectArr);
    },

    // 问答题的判断
    onBlurExplainIpt(e) {
        const { value } = e.detail;
        const { explain, selectArr } = this.data;
        /* 
         * 问答题的判断思路，问答题只有一项，直接判断即可，但是要考虑到，
         * 问答题不可能百分百与答案完全一致，因此，这里规定，答对的关键字，
         * 满足标准答案的一半以上，即为判断正确，在这里我比较了两个字符串的相似度
         */
        const similarity = getSimilarity(value, explain[0].answer);
        // console.log(value, explain[0].answer);
        // console.log(similarity);
        if (selectArr && selectArr.length > 0) {
            // 数组中已经存在值，如果选中同一题，把答案替换了
            if (selectArr.some(item => item.currentIndex == 20)) {
                // 找到在selectArr当前项的下标
                const findId = selectArr.findIndex((item) => item.currentIndex == 20);
                // 替换操作
                if (similarity >= 50) {
                    console.log('true');
                    selectArr.splice(findId, 1, { currentIndex: 20, flag: true, answer: explain[0].answer })
                } else {
                    console.log('false');
                    selectArr.splice(findId, 1, { currentIndex: 20, flag: false, answer: explain[0].answer })
                }
            } else {
                if (similarity >= 50) {
                    console.log('true');
                    selectArr.push({ currentIndex: 20, flag: true, answer: explain[0].answer })
                } else {
                    console.log('false');
                    selectArr.push({ currentIndex: 20, flag: false, answer: explain[0].answer })
                }
            }
        } else {
            // 数组是空的，相当于第一次添加
            if (similarity >= 50) {
                console.log('true');
                selectArr.push({ currentIndex: 20, flag: true, answer: explain[0].answer })
            } else {
                console.log('false');
                selectArr.push({ currentIndex: 20, flag: false, answer: explain[0].answer })
            }
        }
        console.log(selectArr);
    },

    // 其他类型题目的判断
    onBlurOtherIpt(e) {
        const { value } = e.detail;
        const { other, selectArr } = this.data;
        const similarity = getSimilarity(value, other[0].answer);
        // console.log(value, explain[0].answer);
        // console.log(similarity);
        if (selectArr && selectArr.length > 0) {
            // 数组中已经存在值，如果选中同一题，把答案替换了
            if (selectArr.some(item => item.currentIndex == 21)) {
                // 找到在selectArr当前项的下标
                const findId = selectArr.findIndex((item) => item.currentIndex == 21);
                // 替换操作
                if (similarity >= 50) {
                    console.log('true');
                    selectArr.splice(findId, 1, { currentIndex: 21, flag: true, answer: other[0].answer })
                } else {
                    console.log('false');
                    selectArr.splice(findId, 1, { currentIndex: 21, flag: false, answer: other[0].answer })
                }
            } else {
                if (similarity >= 50) {
                    console.log('true');
                    selectArr.push({ currentIndex: 21, flag: true, answer: other[0].answer })
                } else {
                    console.log('false');
                    selectArr.push({ currentIndex: 21, flag: false, answer: other[0].answer })
                }
            }
        } else {
            // 数组是空的，相当于第一次添加
            if (similarity >= 50) {
                console.log('true');
                selectArr.push({ currentIndex: 21, flag: true, answer: other[0].answer })
            } else {
                console.log('false');
                selectArr.push({ currentIndex: 21, flag: false, answer: other[0].answer })
            }
        }
        console.log(selectArr);
    },

    // 显示查看列表按钮
    onShowAnswer(e) {
        this.setData({
            modalName: e.currentTarget.dataset.target
        })
    },

    // 提交
    sumbit(e) {
        console.log(e);
        // console.log('你选择的正确答案', this.data.selectArr);
        // 提交顺序进行排序
        const newArr = this.data.selectArr.sort((a, b) => {
            return a.currentIndex - b.currentIndex;
        });
        console.log(newArr);
        if (newArr.length === 22) {
            this.setData({
                selectArr: [...newArr],
                isRadioSelect: !false,
            }, () => {
                const countDown = this.selectComponent('.control-count-down');
                countDown.pause();
                this.setData({
                    modalName: e.currentTarget.dataset.target
                })
                // console.log('打开抽屉');
            })
        } else {
            Toast.fail('无法提交，题目没有回答完毕');
        }
    },

    // 倒计时结束，考试时间到
    finished(e) {
        this.sumbit(e);
        Toast('考试时间到！');
    },

    hideModal(e) {
        this.setData({
            modalName: null
        })
        console.log('关闭抽屉');
    },

    // 添加更多错题
    toAddQuestion() {
        wx.switchTab({
            url: '../../../pages/index/index',
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        const that = this;
        // 根据上个页面传递过来的课程名，从数据库中抽取数据生成试题
        const { name } = options;
        const gradeDesc = wx.getStorageSync('gradeDesc');
        const { _id } = getUserInfo();
        // 设置导航栏的标题
        wx.setNavigationBarTitle({
            title: `${name}考试`,
        });
        const enterObj = {
            className: name,
            gradeDesc
        }
        // console.log(enterObj);
        // wx.showLoading({
        //     title: '试题生成中...',
        // });
        wx.cloud.callFunction({
            name: 'reqQuestionAPI',
            data: {
                scene: 'GET_QUESTION',
                uid: _id,
                getType: 'classExam',
                enterObj,
            }
        })
            .then(res => {
                console.log(res.result);
                if (res.result) {
                    // wx.hideLoading();
                    const { choice, fill, judgment, explain, other } = res.result;
                    setTimeout(() => {
                        that.setData({
                            showPage: true,
                        }, () => {
                            if (choice.length === 10 && fill.length === 5 && judgment.length === 5 && explain.length === 1 && other.length === 1) {
                                that.setData({
                                    choice,
                                    fill,
                                    judgment,
                                    explain,
                                    other
                                }, () => {
                                    const countDown = that.selectComponent('.control-count-down');
                                    countDown.start();
                                })
                            } else {
                                that.setData({
                                    empty: true,
                                })
                                Toast.fail('未能生成试题，此科目错题数量不足');
                            };
                        })
                    }, 3000)
                } else {
                    Toast.fail('未能生成试题，发生资源错误');
                }
            });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        var circleCount = 0;
        // 心跳的外框动画
        this.animationMiddleHeaderItem = wx.createAnimation({
            duration: 1000, // 以毫秒为单位
            /**
            * http://cubic-bezier.com/#0,0,.58,1
            * linear 动画一直较为均匀
            * ease 从匀速到加速在到匀速
            * ease-in 缓慢到匀速
            * ease-in-out 从缓慢到匀速再到缓慢
            *
            * http://www.tuicool.com/articles/neqMVr
            * step-start 动画一开始就跳到 100% 直到动画持续时间结束 一闪而过
            * step-end 保持 0% 的样式直到动画持续时间结束 一闪而过
            */
            timingFunction: 'linear',
            delay: 100,
            transformOrigin: '50% 50%',
            success: function (res) {
            }
        });
        setInterval(function () {
            if (circleCount % 2 == 0) {
                this.animationMiddleHeaderItem.scale(1.2).step();
            } else {
                this.animationMiddleHeaderItem.scale(1.0).step();
            }
            this.setData({
                animationMiddleHeaderItem: this.animationMiddleHeaderItem.export()
            });
            circleCount++;
            if (circleCount == 1000) {
                circleCount = 0;
            }
        }.bind(this), 1000);
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})